package com.xmtlxx.common.wxap.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * HTTP请求的工具类
 * @author Administrator
 *
 */
public class HttpInvokerUtils {

	/**
	 * GET的HTTP请求
	 * @param urlStr 地址
	 * @param params 参数集
	 * @return
	 * @throws Exception
	 */
	public static String GET(String urlStr) throws Exception {
		HttpURLConnection conn = null;
		BufferedReader reader = null;
		StringBuffer sb = new StringBuffer();
		try {
			URL url = new URL(urlStr);
	        conn = (HttpURLConnection) url.openConnection();
	        conn.connect();
	        reader = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));

	        String line = "";
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if(reader != null){
				reader.close();
			}
			//断开连接
			if(conn != null){
				conn.disconnect();
			}
		}
		return sb.toString();
	}

	/**
	 * POST的HTTP请求
	 * @param urlStr 地址
	 * @param params 参数集
	 * @return
	 * @throws Exception
	 */
	public static String POST(String urlStr, Map<String, String> params,String method) throws Exception {
		HttpURLConnection conn = null;
		BufferedReader reader = null;
		StringBuffer sb = new StringBuffer();
        method = StringUtils.isEmpty(method) ? "POST" : method;
		try {
			URL url = new URL(urlStr);
	        conn = (HttpURLConnection) url.openConnection();
	        conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
	        conn.setRequestMethod(method);// 提交模式
	        conn.setDoOutput(true);// 是否输入参数
	        conn.setUseCaches(false);	//POST不能缓存

	        if(params.keySet().size() > 0){
		        DataOutputStream out = new DataOutputStream(conn.getOutputStream());

		        List<String> paramList = new ArrayList<String>();
		        for (String keyStr : params.keySet()) {
		        	if(params.get(keyStr) != null){
		        		paramList.add(keyStr + "=" + URLEncoder.encode(params.get(keyStr), "utf-8"));
		        	}
				}
		        System.out.println(StringUtils.join(paramList.iterator(), "&"));
		        out.writeBytes(StringUtils.join(paramList.iterator(), "&"));

				out.flush();
				out.close(); // flush and close
	        }

			reader = new BufferedReader(
					new InputStreamReader(conn.getInputStream(), "UTF-8"));

			String line = "";
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if(reader != null){
				reader.close();
			}
			//断开连接
			if(conn != null){
				conn.disconnect();
			}
		}

		return sb.toString();
	}

	/**
	 * POST的HTTP请求
	 * @param urlStr 地址
	 * @param params 参数集
	 * @return
	 * @throws Exception
	 */
	public static String PostToJson(String urlStr, String params) throws Exception {
		HttpURLConnection conn = null;
		BufferedReader reader = null;
		StringBuffer sb = new StringBuffer();
		try {
			URL url = new URL(urlStr);
	        conn = (HttpURLConnection) url.openConnection();
	        conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
	        conn.setRequestMethod("POST");// 提交模式
	        conn.setDoOutput(true);// 是否输入参数
	        conn.setUseCaches(false);	//POST不能缓存

	        if(params != null){
		        DataOutputStream out = new DataOutputStream(conn.getOutputStream());

		        out.write(params.getBytes("UTF-8"));

				out.flush();
				out.close(); // flush and close
	        }

			reader = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));

			String line = "";
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if(reader != null){
				reader.close();
			}
			//断开连接
			if(conn != null){
				conn.disconnect();
			}
		}

		return sb.toString();
	}

	/**
	 * POST提交XML对象
	 * @param document
	 */
	public static Document postXmlClent (String url,Document document) throws Exception {
		Document doc = null;
		try {
			PostMethod post = new PostMethod(url);
	        // 设置请求的内容直接从文件中读取
			InputStream inputStream = new ByteArrayInputStream(document.asXML().getBytes("UTF-8"));
			post.setRequestBody(inputStream);
	        post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);
	        // 指定请求内容的类型
	        post.setRequestHeader("Content-type", "text/xml; charset=UTF-8");
	        HttpClient httpclient = new HttpClient();
	        int result = httpclient.executeMethod(post);
	        InputStream in = post.getResponseBodyAsStream();
	        BufferedReader br = new BufferedReader(new InputStreamReader(in,"UTF-8"));
	        String tempbf;
	        StringBuffer html = new StringBuffer(100);
	        while ((tempbf = br.readLine()) != null) {
	            html.append(tempbf +"\n");
	        }
	        System.out.println("||===InputStream===>"+html.toString());
	        doc = DocumentHelper.parseText(html.toString());

	        post.releaseConnection();
		} catch (Exception e) {
			throw e;
		}
		return doc;
	}
}
